package com.longjianghuasheng.logistics.business.login

import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.lifecycle.MutableLiveData
import com.longjianghuasheng.logistics.entity.LoginResponse
import com.longjianghuasheng.logistics.ext.checkPhone
import com.longjianghuasheng.logistics.ext.commit
import com.longjianghuasheng.logistics.ext.commit2
import com.longjianghuasheng.logistics.ext.toastNormal
import com.longjianghuasheng.logistics.network.apiService
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel

class LoginViewModel : BaseViewModel() {
    var loginType = true

    val result by lazy {
        MutableLiveData<LoginResponse>()
    }

    val mobileObservableField by lazy {
        ObservableField("")
    }

    val codeObservable by lazy {
        ObservableField("")
    }

    val passwordObservable by lazy {
        ObservableField("")
    }

    val startCount by lazy {
        ObservableInt()
    }

    fun onGetCode() {
        val mobile = mobileObservableField.get()
        if (!checkPhone(mobile)) return
        commit({ apiService.get_code(mobile ?: "", 2) }, {
            startCount.set(60)
        })
    }

    fun login() {
        val mobile = mobileObservableField.get()
        val password = passwordObservable.get()
        val code = codeObservable.get()
        if (!checkPhone(mobile)) return

        if (!loginType && code?.isBlank() == true) {
            toastNormal("请填写验证码")
            return
        }

        commit2({
            if (loginType) apiService.login(
                mobile ?: "",
                password ?: ""
            ) else apiService.login_code(mobile ?: "", code ?: "")
        }, result)
    }

}